<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { onMounted, ref } from 'vue'
import { getDictList } from '@/api/common'
import { useUserStore } from '@/stores/user'
import { nameLengthValidator, phoneNumberValidator } from '@/utils/validator'
import { addFeedback } from '@/api/index'
import { upload } from '@/utils/request'

const store = useUserStore()

const form = ref(null)
const complainForm = ref({
  name: '',
  phone: '',
  content: '',
  category: '',
  categoryText: '',
  type: 1,
  files: [],
})

const complainFormRules = {
  name: [
    { required: true, message: '请填写姓名' },
    { message: '姓名至少两个字符', validator: nameLengthValidator },
  ],
  phone: [
    { required: true, message: '请填写联系电话' },
    { validator: phoneNumberValidator, message: '手机号格式有误' },
  ],
  content: [{ required: true, message: '请填写投诉内容' }],
}

const menuItems = ref([])
async function onGetMenuItem() {
  const { result } = await getDictList('feedback.category')
  menuItems.value = result.map(item => ({ name: item.label, value: item.value }))
}
const actionVisible = ref(false)
function chooseItem(item) {
  complainForm.value.category = item.value
  complainForm.value.categoryText = item.name
}

const fileList = ref([])

async function beforeUpload(_, options) {
  try {
    const { id } = await upload(options, {
      module: 'feedback',
      type: 'file',
      single: 'false',
      filetypes: 'jpg,jpeg,png,mp4,doc,docx,pdf',
    })

    complainForm.value.files.push(id)
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

function onDelete(_, __, index) {
  complainForm.value.files.splice(index, 1)
}

const confirmVisible = ref(false)
function onValidate() {
  form.value.validate().then(({ valid }) => {
    if (valid)
      confirmVisible.value = true
  })
}

async function onSubmit() {
  try {
    await uni.showLoading({ title: '请稍后' })
    const { success, message } = await addFeedback(complainForm.value)
    uni.hideLoading()

    if (!success)
      throw new Error(message)
    uni.redirectTo({ url: '/pages/index/view/complaint-success?type=投诉' })
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

onMounted(() => {
  onGetMenuItem()
})

onLoad(() => {
  complainForm.value.name = store.userInfo.realName
  complainForm.value.phone = store.userInfo.phone
})
</script>

<template>
  <view class="bg-[#F5F5F5] pb-safe min-h-safe">
    <nut-navbar title="游客投诉" custom-color="#000" left-show placeholder fixed />
    <view class="mt-2">
      <nut-config-provider :theme-vars="{ 'cellColor': '#000', 'cellAfterBorderBottom': '1px solid #ccc', 'input-disabled-color': '#000' }">
        <nut-form ref="form" :model-value="complainForm" :rules="complainFormRules">
          <nut-form-item label="投&nbsp;诉&nbsp;人" prop="name">
            <nut-input v-model="complainForm.name" placeholder="请输入姓名" type="text" />
          </nut-form-item>
          <nut-form-item label="联系电话" prop="phone">
            <nut-input v-model="complainForm.phone" placeholder="请输入联系电话" type="text" />
          </nut-form-item>
          <nut-form-item label="投诉分类" prop="content">
            <nut-input
              v-model="complainForm.categoryText"
              placeholder="请选择投诉分类"
              type="text"
              disabled
              @click="actionVisible = true"
            >
              <template #right>
                <nut-icon name="arrow-down" size="10" custom-color="#666" />
              </template>
            </nut-input>
          </nut-form-item>
          <nut-form-item label="投诉内容" prop="content">
            <nut-textarea v-model="complainForm.content" placeholder="请输入投诉内容" type="text" max-length="500" limit-show :autosize="{ maxHeight: 200, minHeight: 150 }" />
          </nut-form-item>
        </nut-form>
      </nut-config-provider>
      <view class="px-4 bg-white">
        <view class="mb-4.5">
          <view class="py-2 text-[#666] flex items-center">
            <view class="i-heroicons:paper-clip-solid text-45" />
            <view class="ml-2 text-28">
              附件
            </view>
          </view>
          <nut-config-provider :theme-vars="{ dividerMargin: 0 }">
            <nut-divider :custom-style="{ color: '#ccc' }" />
          </nut-config-provider>
        </view>
        <nut-uploader v-model:file-list="fileList" multiple maximum="2" :before-upload="beforeUpload" @delete="onDelete">
          <template #uploadIcon>
            <nut-icon name="uploader" />
          </template>
        </nut-uploader>
        <view class="py-8.75 flex justify-center">
          <nut-button
            block
            :custom-style="{ width: '350rpx' }"
            custom-color="linear-gradient(to right, #F89201, #F83600)"
            @click="onValidate"
          >
            确认提交
          </nut-button>
        </view>
      </view>
      <nut-action-sheet v-model:visible="actionVisible" :menu-items="menuItems" title="请选择投诉分类" safe-area-inset-bottom @choose="chooseItem" />
      <nut-dialog v-model:visible="confirmVisible" content="确认提交吗?" @ok="onSubmit" />
    </view>
  </view>
</template>

<style scoped>
:deep(.nut-form-item__label) {
  font-weight: 500;
}
</style>
